import React, { useEffect, useRef, useState } from 'react'
import useGetTableData from '@/hooks/useGetTableDataV2'
import SearchForm from '@/components/QsfCustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns } from './TableColumns'
import { DashboardSaleGroupVO as ITableData } from './types'
import CustomTable from '@/components/QsfCustomTable'
import { useNavigate } from 'react-router-dom'
import { useAppSelector } from '@/store/hooks'
import { searchConfig } from './FormConfig'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import './index.less'
import useCachePage from '@/hooks/useCachePage'
import { getDashboardSpuSalePageGroupList, getQuotationSearchCondition } from '@/api/dashboard'
import { getRecentSeventDays } from '@/utils/util'
import { BulbOutlined } from '@ant-design/icons'
import { Button, Empty, Form, Radio, Tooltip, Typography } from 'antd'
const Index: React.FC<{ sentry?: boolean }> = (props) => {
  const navigate = useNavigate()
  const [form] = useForm()
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const { SupplierOption, setSupplierOption, handleSearchSupplier } = useSearchSupplier('supplierId', {
    supplierClassificationCode: '成品供应商',
  })
  const { setCachePage, getCachePage } = useCachePage()
  const [classBig, setclassBig] = useState<IOptionItem[]>([])
  const defaultDateRange = getRecentSeventDays('YYYY-MM-DD')
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const [midClass, setmidClass] = useState<IOptionItem[]>([])
  const [smallClass, setsmallClass] = useState<IOptionItem[]>([])
  const [tinyClass, settinyClass] = useState<IOptionItem[]>([])
  // 1销售额 0销量
  const orderField = useRef<0 | 1 | null>(1)
  // 0 正序 1 倒序
  const orderType = useRef<0 | 1 | null>(1)
  const orderMap: Record<string, any> = {
    saleQty: 0,
    saleAmount: 1,
  }
  const filterOptionsMap: Record<string, any> = {
    0: { key: 'large_class_name', title: '大类' },
    1: { key: 'mid_class_name', title: '中类' },
    2: { key: 'small_class_name', title: '小类' },
    3: { key: 'fine_class_name', title: '细类' },
    4: { key: 'fine_class_name', title: '供应商' },
    5: { key: 'fine_class_name', title: '面种' },
    6: { key: 'fine_class_name', title: '面料' },
    7: { key: 'fine_class_name', title: '设计师/买手' },
    8: { key: 'fine_class_name', title: '风格' },
    9: { key: 'fine_class_name', title: '厚度' },
    10: { key: 'fine_class_name', title: '功能' },
    11: { key: 'fine_class_name', title: '版型' },
    12: { key: 'fine_class_name', title: '面料标签' },
  }
  const [TableColumns, setTableColumns] = useState(filterOptionsMap[0])
  const filterOptions = [
    {
      title: '通用',
      config: [
        { label: '大类', value: 0 },
        { label: '中类', value: 1 },
        { label: '小类', value: 2 },
        { label: '细类', value: 3 },
      ],
    },
    {
      title: '供应链',
      config: [
        { label: '供应商', value: 4 },
        { label: '面种', value: 5 },
        { label: '面料', value: 6 },
      ],
    },
    {
      title: '商品开发',
      config: [
        { label: '设计师/买手', value: 7 },
        { label: '风格', value: 8 },
        { label: '厚度', value: 9 },
        { label: '功能', value: 10 },
        { label: '版型', value: 11 },
        { label: '面料标签', value: 12 },
      ],
    },
  ]

  useEffect(() => {
    setTableColumns(filterOptionsMap[form?.getFieldValue('groupField') || 0])
  }, [form?.getFieldValue('groupField')])
  const { tableProps, params, search, reset, reload } = useGetTableData<ITableData>(getDashboardSpuSalePageGroupList, {
    form: form,
    immediatelySend: false,
    defaultFieldsParams: {
      saleStartDate: defaultDateRange,
      branchOffice: '直营',
      groupField: getCachePage()?.groupField || 0,
      largeClassName: classBig[0]?.value || null,
      excludeSaleAmount: props?.sentry ? true : false,
    },
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
    paramsCallback: (reqParams) => {
      return {
        ...reqParams,
        saleStartDate:
          reqParams.saleStartDate && reqParams.saleStartDate.length === 2 ? reqParams.saleStartDate[0] : null,
        saleEndDate:
          reqParams.saleStartDate && reqParams.saleStartDate.length === 2 ? reqParams.saleStartDate[1] : null,
        orderField: orderField.current,
        orderType: orderType.current,
      }
    },
  })
  useEffect(() => {
    getOptions()
  }, [])
  const handleCacheData = async (biglist?: IOptionItem[]) => {
    const cacheData = getCachePage()
    if (cacheData == null) {
      if (biglist && biglist.length > 0) {
        form.setFieldValue('largeClassName', biglist?.[0]?.value)
      }
      await form.validateFields()
      // search()
      setCachePage({ ...params, largeClassName: biglist?.[0]?.value || null })
    } else {
      const { SupplierOption, ...resetCacheData } = cacheData
      // 先重置表单再设置缓存！！！
      form.resetFields()
      form.setFieldsValue({
        ...resetCacheData,
      })
      setSupplierOption(SupplierOption || [])
      // reload({ ...resetCacheData })
    }
  }
  const onBigClassIdChange = (_: string, item: any) => {
    const bigClassId = item?.bigClassId || null
    bigClassId && getOptions(bigClassId)
    form.setFieldsValue({
      smallClassNameList: null,
      fineClassNameList: null,
    })
  }
  const onBigClassIdClear = () => {
    form.setFieldsValue({
      smallClassNameList: null,
      fineClassNameList: null,
    })
    setsmallClass([])
    settinyClass([])
  }
  const getOptions = async (bigClassId?: string) => {
    const res = await getQuotationSearchCondition({ bigClassId })
    if (res.code == 200) {
      if (bigClassId === undefined) {
        if (res.data.bigClassList && res.data.bigClassList.length > 0) {
          const biglist = res.data?.bigClassList?.map((item: any) => {
            return {
              label: item.className,
              value: item.className,
              bigClassId: item.classConfigId,
            }
          })
          setclassBig(biglist)
          handleCacheData(biglist)
        }
        if (res.data.midClassList && res.data.midClassList.length > 0) {
          setmidClass(res.data.midClassList)
        }
        return
      }
      if (res.data.smallClassList && res.data.smallClassList.length > 0) {
        setsmallClass(res.data.smallClassList)
      }
      if (res.data.tinyClassList && res.data.tinyClassList.length > 0) {
        settinyClass(res.data.tinyClassList)
      }
    }
  }
  const getFilterOptions = () => {
    return (
      <div className="dsw_custom_filter_wrap">
        {filterOptions.map((item, index) => {
          return (
            <div key={item?.title} className="dsw_custom_filter_items">
              <div className="dsw_cfw_title">
                <span>{item?.title}</span>
                {index === 0 && (
                  <Typography.Link
                    disabled={tableProps.loading}
                    onClick={() => {
                      const { groupField, ...cacheData } = getCachePage()
                      form.setFieldsValue({
                        groupField: 0,
                      })
                      setCachePage({
                        ...cacheData,
                        groupField: 0,
                        current: 1,
                      })
                      search()
                    }}
                  >
                    重置
                  </Typography.Link>
                )}
              </div>
              <div className="dsw_cfw_radio_box">
                <Form form={form}>
                  <Form.Item noStyle name="groupField">
                    <Radio.Group
                      options={item?.config || []}
                      disabled={tableProps.loading}
                      onChange={(event) => {
                        const cacheData = getCachePage()
                        setCachePage({
                          ...cacheData,
                          groupField: event?.target?.value,
                          current: 1,
                        })
                        search()
                      }}
                    />
                  </Form.Item>
                </Form>
              </div>
            </div>
          )
        })}
      </div>
    )
  }
  const handleTableChange = (_: any, __: any, sorter: any) => {
    orderField.current = orderMap[sorter?.field] != undefined ? orderMap[sorter?.field] : null
    orderType.current = sorter?.order === 'ascend' ? 0 : sorter?.order === 'descend' ? 1 : null
    search()
  }
  return (
    <PageContainer className="dashboard_salesanalysis_wrap">
      <SearchForm
        loading={tableProps.loading}
        form={form}
        searchConfig={searchConfig({
          SupplierOption,
          handleSearchSupplier,
          classBig,
          DICTDATA,
          onBigClassIdChange,
          onBigClassIdClear,
          midClass,
          smallClass,
          tinyClass,
          form,
        })}
        onFinish={async () => {
          const { groupField } = form.getFieldsValue()
          const cacheData = getCachePage()
          setCachePage({
            ...form.getFieldsValue(),
            groupField: groupField || cacheData?.groupField || 0,
            SupplierOption,
            current: 1,
            size: params.size,
          })
          search()
        }}
        onReset={() => {
          reset({ largeClassName: classBig?.[0]?.value || null, groupField: 0 })
          setCachePage({
            current: 1,
            size: 10,
            groupField: 0,
            saleStartDate: defaultDateRange,
            branchOffice: '直营',
            largeClassName: classBig?.[0]?.value || null,
          })
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex dsw_dropdown_custom_class">
              <Tooltip
                overlayInnerStyle={{ width: 'max-content' }}
                getPopupContainer={() => document.querySelector('.dsw_dropdown_custom_class')!}
                arrow={false}
                title={getFilterOptions()}
                placement="right"
                onOpenChange={(show) => {
                  if (show) {
                    const cacheData = getCachePage()
                    const { groupField } = form.getFieldsValue()
                    form.setFieldsValue({
                      groupField: groupField || cacheData?.groupField || 0,
                    })
                  }
                }}
              >
                <Button icon={<BulbOutlined />}>分析维度：{TableColumns.title}</Button>
              </Tooltip>
            </div>
          </div>
        }
      ></SearchForm>
      <CustomTable
        stripe={false}
        isAutoScrollY
        {...tableProps}
        columns={useIndexColumns({ navigate, TableColumns, isSentry: !!props?.sentry })}
        rowKey={(rows) => rows?.groupKey}
        onChange={handleTableChange}
        locale={{
          emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据，请点击查询"></Empty>,
        }}
      ></CustomTable>
    </PageContainer>
  )
}

export default Index
